package com.fbd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbd.dto.DishDto;
import com.fbd.entity.Dish;
import com.fbd.entity.DishFlavor;
import com.fbd.service.DishFlavorService;
import com.fbd.mapper.DishMapper;
import com.fbd.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    public DishFlavorService dishFlavorService;
    @Transactional //事务注解
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 将菜品存入数据库
        this.save(dishDto);
        // 将菜品的ID写入flavor中
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor:flavors){
            flavor.setDishId(dishDto.getId());
        }
        //将带有菜品id的口味信息存入数据库中
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //根据id查找对应的菜品
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //查询对应的口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional //事务注解
    public void updateByIdWithFlavor(DishDto dishDto) {
        //根据id修改dish表
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //删除旧的口味数据
        dishFlavorService.remove(queryWrapper);

        //将新的数据写入数据库中
        // 将菜品的ID写入flavor中
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor:flavors){
            flavor.setDishId(dishDto.getId());
        }
        //将带有菜品id的口味信息存入数据库中
        dishFlavorService.saveBatch(flavors);
    }
}
